package com.jt.tenant.widget;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jt.tenant.R;
import com.jt.tenant.app.JTApplication;

public class ShopCount extends LinearLayout {

	private static int CURRENT_NUM = 0;

	public static void SendCount(Context context, int num) {
		context.sendBroadcast(new Intent(Receiver.ACTION).putExtra(
				Receiver.KEY, num));
	}

	private TextView count;
	private Receiver receiver = new Receiver();

	public ShopCount(Context context, AttributeSet attrs) {

		super(context, attrs);

		LayoutInflater.from(context).inflate(R.layout.view_shop_count, this);

		count = (TextView) JTApplication.ScaleScreenHelper.loadViewWidthHeight(findViewById(R.id.shop_count),40,40);

		setCount(CURRENT_NUM);
	}

	// 当视图可见的时候走的方法
	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		getContext().registerReceiver(receiver,
				new IntentFilter(Receiver.ACTION));
	}

	// 当视图被移除屏幕的时候
	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		getContext().unregisterReceiver(receiver);
		CURRENT_NUM = 0;
	}

	private void setCount(int num) {
		setVisibility(num == 0 ? View.INVISIBLE : View.VISIBLE);
		count.setText(num + "");
	}

	private class Receiver extends BroadcastReceiver {

		public static final String ACTION = "shopcount";
		public static final String KEY = "num";

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			setCount(CURRENT_NUM = arg1.getIntExtra(KEY, 0));
		}
	}

}
